package com.yc.privilege.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yc.privilege.entity.Role;
import com.yc.privilege.entity.RoleFunction;
import com.yc.privilege.entity.UserRole;
import com.yc.privilege.mapper.RoleMapper;
import com.yc.privilege.service.RoleFunctionservice;
import com.yc.privilege.service.Roleservice;
import com.yc.privilege.service.UserRoleservice;
@Service("roleservice")
public class Roleserviceimpl implements Roleservice {
	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private RoleFunctionservice roleFunctionservice;
	
	@Autowired
	private UserRoleservice userRoleservice;
	@Override
	public List<Role> findTwoFunctionById(int uid) {
		return roleMapper.findTwoFunctionById(uid);
	}

	@Override
	public int saveRole(Role role) {
		return roleMapper.saveRole(role);
	}

	@Override
	public int deleteRoleById(int rid) {
		return roleMapper.deleteRoleById(rid);
	}

	@Override
	public int updateRole(Role role) {
		return roleMapper.updateRole(role);
	}

	@Override
	public List<Role> findRolesByPages(int page, int size) {
		return roleMapper.findRolesByPages(page,size);
	}

	/**
	 * 注意这里要做事务处理
	 * @param fids，功能id字符串数组
	 * @param rname：功能名
	 * @param uid:登陆的用户的id
	 * @return
	 */
	@Override
	public boolean addRole(String fids, String rname,int uid) {
		Role role = new Role(rname);
		int result = 0;
		try {//捕获插入相同用户名的异常
			result = roleMapper.saveRole(role);
		} catch (Exception e) {
				e.printStackTrace();
				return false;
		}
		if(result>0){
			UserRole userRole = new UserRole(role.getRid(),uid);
			//用户创建角色，则保证这个角色属于这个用户，所以用户角色表需要添加相关记录
			boolean result2 = userRoleservice.saveUserRole(userRole);
			if(result2){
				List<RoleFunction> list=new ArrayList<RoleFunction>();
				int role_id = role.getRid();
				RoleFunction roleFunction=null;
				String[] strs = fids.split(",");
				int j=strs.length;
				for(int i=0;i<j;i++){
					roleFunction=new RoleFunction(role_id,Integer.parseInt( strs[i]));
					list.add(roleFunction);
				}
				//创建角色同时必须赋予角色功能（权限）信息，否则角色是没有权限
			    int result3 = roleFunctionservice.saveRoleFunction(list);
				if(j==result3){
					return true;
				}
			}
		}
		return false;
	}

@Override
public List<Role> selRoles(int uid) {
	return roleMapper.selRoles(uid);
}

}
